package CartService

import (
	"context"
	"fmt"
	"gdshop-back-end-go/client-api/app/request/CartReq"
	"gdshop-back-end-go/client-api/app/response/CartResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-order/OrderService"
	"gdshop-back-end-go/service-other/GoodsActivityService"
	"github.com/gogf/gf/frame/g"
	"github.com/syyongx/php2go"
	"sort"
)

func My(ctx context.Context, parames *CartReq.My) *response.JsonResponse {
	cartList := []*CartResp.Details{}
	count, countErr := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"member_cart").Where("delete_at<1 AND member_id=?", parames.MemberId).Fields(
		"1").Count()
	if countErr != nil {
		return response.FailByRequestMessage(nil, countErr.Error())
	}

	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_cart").Page(
		parames.Page, parames.PageSize,
	).Where("member_id=?", parames.MemberId).Structs(&cartList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	respList := CartResp.List{
		PageInfo: tools.GetPageInfo(count, parames.Page, parames.PageSize),
	}
	if count > 0 {
		// 处理返回数据
		for _, item := range cartList {
			handleDetails(ctx, item)
		}
	}
	respList.List = cartList
	return response.SuccessByRequestMessageData(nil, "成功", respList)
}

func MyByGroup(ctx context.Context, parames *CartReq.My) *response.JsonResponse {
	cartList := []*CartResp.Details{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_cart").
		Where("member_id=?", parames.MemberId).Structs(&cartList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 处理返回数据
	for _, item := range cartList {
		handleDetails(ctx, item)
	}
	// 记录每个商品有几个活动
	goodsActivityNums := g.MapIntInt{}
	// 禁用的购物车 IDS
	disableCartIds := []int{}
	tmpArr := map[int]*CartResp.CartActivityGroupItem{}
	// 商品归类
	for _, item := range cartList {
		if item.IsDisable == 1 {
			// 禁用的商品，不检测
			disableCartIds = append(disableCartIds, item.Id)
			continue
		}
		activitys, err := GoodsActivityService.GetGoodsActivityByGoodsId(ctx, item.GoodsId)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}

		// 记录每个商品有几个活动
		goodsActivityNums[item.Id] = len(activitys)

		// 先写入每件价格
		// Paid 实付要乘以数量
		item.Paid = item.SellPrice * int64(item.Total)

		// 如果符合的数量小于 1 跳过
		if len(activitys) < 1 {
			continue
		}
		var activityByGoodsId *entity.GoodsActivity
		// 如果数据库里面有记录活动ID，则选用记录的
		if item.ActivityId > 0 {
			for _, ggg := range activitys {
				if ggg.Id == item.ActivityId {
					activityByGoodsId = ggg
				}
			}
			// 如果还是没有，则选用最优惠活动
			if activityByGoodsId == nil {
				activityByGoodsId = activitys[0]
			}
		} else {
			// 未记录，选用最优惠的
			// 经过排序 0 下标 是最优惠的活动
			activityByGoodsId = activitys[0]
		}
		if _, ok := tmpArr[activityByGoodsId.Id]; !ok {
			tmpArr[activityByGoodsId.Id] = &CartResp.CartActivityGroupItem{
				ActivityId:   activityByGoodsId.Id,
				ActivityName: activityByGoodsId.ActivityTag,
				Remark:       activityByGoodsId.Remark,
				Sort:         activityByGoodsId.Sort,
				Type:         GoodsActivityService.GetActivityTagTypeStr(activityByGoodsId),
				GoodsIds:     []int{},
				CartIds:      []int{},
				TmpActivity:  activityByGoodsId,
			}
		}

		if !php2go.InArray(item.GoodsId, tmpArr[activityByGoodsId.Id].GoodsIds) {
			tmpArr[activityByGoodsId.Id].GoodsIds = append(tmpArr[activityByGoodsId.Id].GoodsIds, item.GoodsId)
		}
		if !php2go.InArray(item.Id, tmpArr[activityByGoodsId.Id].CartIds) {
			tmpArr[activityByGoodsId.Id].CartIds = append(tmpArr[activityByGoodsId.Id].CartIds, item.Id)
		}
		// 更新购物车活动ID
		if item.ActivityId != activityByGoodsId.Id {
			updateCartActivityId(ctx, activityByGoodsId.Id, item.Id)
		}
	}
	// 根据活动分组
	groups := []*CartResp.CartActivityGroupItem{}
	activityGroupCartIds := []int{}
	for _, item := range tmpArr {
		// 计算本分组总优惠金额
		var tmpCart []*CartResp.Details
		for _, ccc := range cartList {
			if php2go.InArray(ccc.Id, item.CartIds) {
				//discountPrice += ccc.DiscountPrice

				// 计算勾选了的商品 到手价
				if ccc.IsSelected == 1 {
					// 取出需要处理的
					tmpCart = append(tmpCart, ccc)
				}
			}
		}
		discountPrice, err := OrderService.GoodsActivityByCartModel(tmpCart, item.TmpActivity)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		item.DiscountPrice = discountPrice
		groups = append(groups, item)
		// 标注出已经存在的商品ID
		activityGroupCartIds = append(activityGroupCartIds, item.CartIds...)
	}
	// 无活动项
	notActivityGroupCartIds := []int{}
	for _, item := range cartList {
		if !php2go.InArray(item.Id, activityGroupCartIds) && !php2go.InArray(item.GoodsId, disableCartIds) {
			notActivityGroupCartIds = append(notActivityGroupCartIds, item.Id)
		}
	}

	// 添加一个没有活动的活动
	if len(notActivityGroupCartIds) > 0 {
		groups = append(groups, &CartResp.CartActivityGroupItem{
			ActivityId:   -1,
			ActivityName: "自营",
			Sort:         0,
			CartIds:      notActivityGroupCartIds,
		})
	}
	// 如果有禁用的商品，单独加一个分组
	if len(disableCartIds) > 0 {
		groups = append(groups, &CartResp.CartActivityGroupItem{
			ActivityId:   -2,
			Sort:         -1,
			ActivityName: "过期",
			CartIds:      disableCartIds,
		})
	}

	// 整理 groups 排序
	sort.Slice(groups, func(i, j int) bool {
		return groups[i].Sort > groups[j].Sort
	})

	for _, item := range cartList {
		// 预估每件到手价
		item.PracticalPrice = item.Paid / int64(item.Total)
		// 当前未放开，所以先做默认处理
		item.BuyStep = 1
		item.BuyMin = 1
		item.BuyMax = 100
	}

	resMap := g.Map{
		"goodss":         cartList,
		"groups":         groups,
		"activityNums":   goodsActivityNums,
		"photo_base_url": g.Cfg().GetString("site.PhotoUrlProfix"),
	}

	return response.SuccessByRequestMessageData(nil, "成功", resMap)
}

func handleDetails(ctx context.Context, item *CartResp.Details) {
	var goodsModel *entity.Goods
	err := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"goods").Where("id", item.GoodsId).Struct(&goodsModel)

	item.GoodsCover = "未找到商品图片"
	if err != nil {
		item.GoodsName = "未找到商品"
	}
	if goodsModel != nil {
		item.GoodsName = goodsModel.GoodsName
		//item.GoodsCover = g.Cfg().GetString("site.PhotoUrlProfix") + goodsModel.Cover
		item.GoodsCover = goodsModel.Cover
		item.GoodsStatus = goodsModel.Status
		if goodsModel.Status == 0 {
			item.IsSelected = 0
			item.IsDisable = 1
		}
	}
	var goTmp *entity.GoodsOption
	err = toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"goods_option").Where("id", item.GoodsOptionId).Struct(&goTmp)
	if err != nil || goTmp == nil {
		item.OptionName = "未找到规格"
		// 没有找到规格也禁用
		item.IsSelected = 0
		item.IsDisable = 1
	} else {
		item.OptionName = goTmp.Title
		// 判断规格库存是否为0
		if goTmp.Stock < 1 {
			item.IsSelected = 0
			item.IsDisable = 1
		} else {
			// 如果 用户添加的数量大于库存，自动更新为最大库存
			if item.Total > goTmp.Stock {
				item.Total = goTmp.Stock
			}
		}
	}
	item.MarketPrice = goTmp.MarketPrice
	item.SellPrice = goTmp.SellPrice
	item.Checked = item.IsSelected == 1
	item.ShowPrice = fmt.Sprintf("%.2f", float64(item.SellPrice)/float64(100))
}

// 更新购物车活动ID，第一期先主动更新，后面开放购物车界面自主选择活动后，选择完活动，即刻写入表
func updateCartActivityId(ctx context.Context, activityId int, id int) {
	_, err := toolsDb.GetUnSafaTable(ctx, "member_cart").Where("id", id).Update(g.Map{
		"activity_id": activityId,
	})
	if err != nil {
		return
	}
}
